package com.hyperf.core.shardingjdbc;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;

/**
 * 数据库分表策略
 *
 * <p>
 * 参数结构
 * availableTargetNames ["t_order_item_1", "t_order_item_2"]
 * shardingValue {logicTableName:"t_order_item", columnName:"order_id", value:0}
 * </p>
 *
 * @author lizhaoyang
 */
@SuppressWarnings("all")
public class PreciseShardingTableAlgorithm implements PreciseShardingAlgorithm {

    private final static String TABLE_NAME_UNDERLINE = "_";

    @Override
    public String doSharding(Collection availableTargetNames, PreciseShardingValue shardingValue) {
        int tableIndex = getTableIndex(availableTargetNames.size(), shardingValue.getValue());
        for (Object availableTargetName : availableTargetNames) {
            String tableName = String.valueOf(availableTargetName);
            if (tableName.endsWith(TABLE_NAME_UNDERLINE + tableIndex)) {
                return tableName;
            }
        }

        throw new UnsupportedOperationException();
    }

    /**
     * 计算sharding对应的表索引
     *
     * @param tableCount  分表数量
     * @param columnValue 分片键value
     * @return 表索引
     */
    public int getTableIndex(int tableCount, Object columnValue) {
        return Math.abs(columnValue.hashCode()) % tableCount;
    }
}
